package cn.poka.device;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import poka_global_constant.GlobalConstant;
import cn.poka.util.DeviceInfo;

import android_serialport_api.SerialPort;

public class ScanDevice {

	private static ScanDevice scanDevice;

	private static SerialPort scanSerialPort;

	/** 通过Scan序列化接口，得到命令输入流 */
	private static InputStream mInput;

	/** 通过Scan序列化接口，得到命令输出流 */
	private static OutputStream mOutput;

	/** Scan设备 IO口一 */
	private static GPIO powerIO;

	private ScanDevice(){

	}

	/**
	 * 获取RFID设备实例，如果实例为空，则进行初始化
	 * @return
	 */
	public static ScanDevice getInstance(){
		if(scanDevice == null){
			if(scanSerialPort == null){
				File rfidFile = new File(DeviceInfo.SCAN_FILE);
				try {
					scanSerialPort = new SerialPort(rfidFile,
							DeviceInfo.SCAN_DEVICE_KEY, 0);

					powerIO = new GPIO(GlobalConstant.IO_SCAN_POWER);

					mInput = scanSerialPort.getInputStream();
					mOutput = scanSerialPort.getOutputStream();

					scanDevice = new ScanDevice();
				} catch (SecurityException e) {
					e.printStackTrace();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		}

		return scanDevice;
	}

	/**
	 * 给RFID设备上电
	 */
	public void enable(){
		if(powerIO != null){
			powerIO.setGPIO(GlobalConstant.ENABLE_IO);
		}
	}

	/**
	 * 给RFID设备断电
	 */
	public void disenable(){
		if(powerIO != null){
			powerIO.setGPIO(GlobalConstant.DISABLE_IO);
		}
	}

	/**
	 * 关闭RFID设备
	 */
	public void close(){
		if(scanSerialPort != null){
			scanSerialPort.close();
			scanSerialPort = null;
			try {
				mInput.close();
				mOutput.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if(scanDevice != null){
			scanDevice = null;
		}
	}

	/**
	 * 读取响应帧
	 * @return
	 */
	public byte[] read(){
		byte[] responseData = null;
		byte[] response = null;
		int available = 0 ;
		int index = 0;
		int headIndex = 0;
		//500ms内轮询无数据则，无数据返回
		try {
			while(index < 10){
				Thread.sleep(50);
				available = mInput.available();
				//缓冲区有数据
				if(available > 7) break;
				index++;
			}
			if(available > 0){
				responseData = new byte[available];
				mInput.read(responseData);
				for(int i = 0; i < available; i++){

//				if(responseData[i] == WIRELESS_HEAD){
//					headIndex = i;
//					break;
//				}
				}
				response = new byte[available - headIndex];
				System.arraycopy(responseData, headIndex, response, 0, response.length);

			}
		} catch (Exception e1) {
			e1.printStackTrace();
		}

		return response;
	}


}












































